import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:堆
 * User: LXW
 * Date: 2022-03-01
 * Time: 9:18
 */
public class MyHeap {
    public int[] elem;
    public int size;
    public MyHeap() {
        this.elem = new int[10];
    }

    /**
     * 向下调整
     * @param parent 根节点
     * @param len  数组长度
     */
    public void shiftDown(int parent,int len) {
        int child = 2*parent + 1;
        while(child < len) {
            if(child+1 < len && elem[child] < elem[child+1]) {
                child++;
                if(elem[child] > elem[parent]) {
                    int tmp = elem[child];
                    elem[child] = elem[parent];
                    elem[parent] = tmp;
                    parent = child;   // 这里要注意，如果第一个if进来了说明此时的child就是右孩子，否则是左孩子。
                }else {
                    break;
                }
            }
        }
    }
    public void createHead(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            size++;
        }
        for (int parent = (elem.length-1-1)/2; parent >= 0 ; parent--) {
            shiftDown(parent,size);
        }
    }
    public void shiftUp(int child) {
        int parent = (child-1)/2;
        while(child == 0) {
            if(elem[child] > elem[parent]) {
                int tmp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = tmp;
                child = parent;
                parent = (parent-1)/2;
            }else {
                break;
            }
        }
    }
    public void offer(int val) {
        if(isFull()) {
            this.elem = Arrays.copyOf(elem,2*elem.length);
        }
        this.elem[size-1] = val;
        size++;
    }
    public boolean isFull() {
        return size == elem.length;
    }
    public int poll() {
        if(isEmpty()) {
            throw new RuntimeException("优先级队列为空");
        }
        int tmp = elem[0];
        elem[0] = elem[size-1];
        elem[size-1] = tmp;
        size--;
        shiftDown(0,size);
        return tmp;
    }
    public boolean isEmpty() {
        return size == 0;
    }
    public int peek() {
        if(isEmpty()) {
            throw new RuntimeException("优先级队列为空");
        }
        return elem[0];
    }
}
